import fs from "fs";
import path from "path";
import { program } from "commander";
import ora from "ora";

import download from "download-git-repo";
import { VUE_REPO } from "../config/repo.js";
import promptQuestions from "./prompts.js";
import { execCommand } from "../utils/exec-command.js";
import { logDebug, logError, logHighlight, logInfo, logSuccess, logWarning } from "../utils/logger.js";
import { compileEjs } from "../utils/compile-ejs.js";
import { writeFile } from "../utils/file.js";

const spinner = ora();

async function createProjectAction(project) {
    try {
        // 1.从编写的项目模板中clone下来项目
        // 下载loading动画
        spinner.start("正在下载模板...");
        // await download(VUE_REPO, project, { clone: true });
        spinner.succeed("下载完毕！");

        // 2.很多的脚手架, 都是在这里给予提示
        logInfo("🚀 项目初始化完成");
        logHighlight("npm install");
        logHighlight("npm run dev");
        // console.log(`cd ${project}`);
        // console.log(`npm install`);
        // console.log(`npm run dev`);

        logInfo("这是一条信息日志");
        logSuccess("这是一条成功日志");
        logWarning("这是一条警告日志");
        logError("这是一条错误日志");
        logDebug("这是一条调试日志");
        logHighlight("这是一个高亮信息");

        await promptQuestions();

        // 3.帮助执行npm install
        console.log(process.platform);
        // const commandName = process.platform === "win32" ? "npm.cmd" : "npm";
        // await execCommand(commandName, ["install"], { cwd: `./${project}` })
        await execCommand("npm", ["--version"]);

        // // 4.帮助执行npm run dev
        // await execCommand(commandName, ["run", "dev"], { cwd: `./${project}` })
    } catch (error) {
        spinner.fail("模板下载失败");
        console.log("github连接失败, 请稍后重试");
    }
}

async function addComponentAction(cpnname) {
    try {
        // 1.创建一个组件: 编写组件的模板, 根据内容给模板中填充数据
        const resultStr = await compileEjs("component.vue.ejs", {
            name: cpnname,
            lowername: cpnname.toLowerCase()
        });

        // 2.将result写到到对应的文件夹中，默认为当前目录
        const destinationFolder = program.opts().dest || "./";
        
        const filepath = path.join(destinationFolder, `${cpnname}.vue`);
        await writeFile(filepath, resultStr);

        logSuccess(`创建组件成功: ${filepath}`);
    } catch (error) {
        logError(error);
    }
}

export { createProjectAction, addComponentAction };
